﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using kwzx.Common;

namespace kwzx
{
    public partial class dbrw_fpkh : Form
    {
        DataSet1TableAdapters.K_DeviceIssueTableAdapter k_deviceIssue = new DataSet1TableAdapters.K_DeviceIssueTableAdapter();
        DataSet1TableAdapters.CD_CardTypeTableAdapter cd_card = new DataSet1TableAdapters.CD_CardTypeTableAdapter();
        DataSet1TableAdapters.K_kwzxrwTableAdapter kwzxrw = new DataSet1TableAdapters.K_kwzxrwTableAdapter();
        DataSet1TableAdapters.T_BMTableAdapter t_bm = new DataSet1TableAdapters.T_BMTableAdapter();
        DataSet1TableAdapters.K_CardTableAdapter k_card = new DataSet1TableAdapters.K_CardTableAdapter();
        DataSet1TableAdapters.T_USERTableAdapter t_user = new DataSet1TableAdapters.T_USERTableAdapter();

        int userid = 0;
        int kwzxrwid = 0;
        public dbrw_fpkh()
        {
            InitializeComponent();
        }

        public dbrw_fpkh(int kwzxrwid1, int userid1)
        {
            userid = userid1;
            kwzxrwid = kwzxrwid1;
            InitializeComponent();
        }

        private void fpcardno_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“dataSet1.X_CS_DETAIL”中。您可以根据需要移动或删除它。
            this.x_CS_DETAILTableAdapter.Fill(this.dataSet1.X_CS_DETAIL);

            //表T_USER，加载参数userid的用户信息
            this.t_USERTableAdapter.FillBy_ID(this.dataSet1.T_USER, userid);

            //加载卡片表记录
            this.cD_CardTypeTableAdapter.Fill(this.dataSet1.CD_CardType); 
            
            //表k_carddata 发卡日志表，加载参数userid的发卡日志
            this.k_CarddataTableAdapter.FillBy_user_id(this.dataSet1.K_Carddata, Convert.ToInt32(userid));

            if (t_USERBindingSource.Current != null)
            {
                string users_id9 = ((DataRowView)t_USERBindingSource.Current)["user_id"].ToString();
                string Imgpath = ((DataRowView)t_USERBindingSource.Current)["zp"].ToString(); ;
                if (!string.IsNullOrWhiteSpace(Imgpath))
                {
                    int x = Imgpath.IndexOf("ftp/") + 4;
                    string userImg = Imgpath.Substring(x, Imgpath.Length - x);   //ftp下载路径
                    int userImginfo = userImg.IndexOf("/") + 1;

                    string zpname = users_id9 + ".dat";
                    string kkzp = FileTran.DownloadFile(SPicUtils.path, zpname, userImg);
                    this.pictureBox1.Image = SPicUtils.PicConvert(kkzp);
                }
            }
            else
            {
                pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
            }

            //如果待办任务表里的人员信息在人员库里能够查到记录的话，则去卡表查询，否则提示人员已被删除，任务结束
            DataTable dt_user = t_user.GetDataBy_ID(userid);
            if (dt_user.Rows.Count < 1)
            {
                //
                MessageBox.Show("人员信息已被删除。任务结束！");
                //更新K_kwzxrw记录
                kwzxrw.UpdateQuery_czzt("已手动完成-人员被删除任务结束", kwzxrwid);
                this.Close();
            }
            else
            {
                //如果k_card表中存有记录表示，该用户发过卡，否则用户没有配过卡。
                if (k_CardTableAdapter.GetDataBy_user_id(Convert.ToInt32(userid)).Rows.Count > 0)
                {
                    this.k_CardTableAdapter.FillBy_user_id(this.dataSet1.K_Card, Convert.ToInt32(userid));
                    this.mess.Text = "该用户已分配过卡，需退卡后，方可发卡！";
                    this.button1.Enabled = false;
                }
                else
                {
                    //this.k_CardBindingSource.AddNew();
                    this.mess.Text = "";
                    this.button1.Enabled = true;

                    //获取部门名称
                    DataTable t_bmdt = t_bm.GetDataBy_DEPT_id(int.Parse(((DataRowView)t_USERBindingSource.Current)["dept_id"].ToString()));
                    dEPT_idTextBox.Text = t_bmdt.Rows[0]["bmmc"].ToString();


                    string user_uby = ((DataRowView)t_USERBindingSource.Current)["uby"].ToString();//获取人员的归属来判断是否是正式员工及部门、归属的名称
                    if (user_uby == "-1")//-1为正式员工
                    {
                        comboBox1.Text = "正式员工(蓝卡)";
                        uBYTextBox.Text = "";//设置归属部门为空
                    }
                    else
                    {
                        if (user_uby == "335")//335为访客
                        {
                            comboBox1.Text = "访客(黄卡)";
                        }
                        else
                        {
                            comboBox1.Text = "非正式员式(绿卡)";
                        }
                        //获取归属部门
                        DataTable t_ubydt = t_bm.GetDataBy_DEPT_id(int.Parse(((DataRowView)t_USERBindingSource.Current)["uby"].ToString()));
                        uBYTextBox.Text = t_ubydt.Rows[0]["bmmc"].ToString();
                    }
                    string CT_ID = "2";
                    try
                    {
                        CT_ID = comboBox1.SelectedValue.ToString();
                    }
                    catch (Exception ex)
                    {
                    }
                    //查询卡类型有效时间
                    DataTable dtct = cd_card.GetDataBy_CT_ID(int.Parse(CT_ID));
                    string CT_DefaultUseDate = "";
                    string CT_Pressure = "0";
                    string CT_UseDUD = "";
                    string CT_Mark = "";
                    if (dtct.Rows.Count > 0)
                    {
                        CT_Pressure = dtct.Rows[0]["CT_Pressure"].ToString();
                        double k = double.Parse(CT_Pressure);
                        yjTextBox.Text = (Convert.ToInt32(k)).ToString();

                        CT_UseDUD = dtct.Rows[0]["CT_UseDUD"].ToString();
                        CT_Mark = dtct.Rows[0]["CT_Mark"].ToString();
                        CT_DefaultUseDate = dtct.Rows[0]["CT_DefaultUseDate"].ToString();
                        CT_Pressure = dtct.Rows[0]["CT_Pressure"].ToString();
                    }
                    //日期
                    string fromdate = "";
                    string to_date = "";
                    if (CT_UseDUD == "False")
                    {
                        fromdate = DateTime.Now.ToString(); ;
                        to_date = DateTime.Now.AddYears(30).ToString(); ;
                    }
                    else
                    {
                        fromdate = DateTime.Now.ToString();
                        if (CT_Mark == "0")//日
                        {
                            double zq = double.Parse(CT_DefaultUseDate);
                            to_date = DateTime.Now.AddDays(zq).ToShortDateString();
                        }
                        if (CT_Mark == "1")//周
                        {
                            double zq = double.Parse(CT_DefaultUseDate) * 7;
                            to_date = DateTime.Now.AddDays(zq).ToShortDateString();
                        }
                        if (CT_Mark == "2")//月
                        {
                            int zq = int.Parse(CT_DefaultUseDate);
                            to_date = DateTime.Now.AddMonths(zq).ToShortDateString();
                        }
                        if (CT_Mark == "3")//年
                        {
                            int zq = int.Parse(CT_DefaultUseDate);
                            to_date = DateTime.Now.AddYears(zq).ToShortDateString();
                        }
                    }
                    fdateDateTimePicker.Text = fromdate;
                    jdateDateTimePicker.Text = to_date;

                    kztComboBox.Text = "发卡";

                }
            }
        }
        /// <summary>
        /// 发卡操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (khTextBox.Text.Length > 10 || khTextBox.Text.Length < 10)
            {
                MessageBox.Show("卡号不正确！");
                return;
            }
            if (this.khTextBox.Text == "")
            {
                MessageBox.Show("未分配卡号，请先读取卡号！");
                return;
            }
            string kh = khTextBox.Text.Trim();
            DataSet1TableAdapters.K_CardTableAdapter kc = new DataSet1TableAdapters.K_CardTableAdapter();
            DataTable dtbl = kc.GetDataBy_kh(kh);
            if (dtbl.Rows.Count > 0)
            {
                MessageBox.Show("此卡号已分配过了(重复)");
                return;
            }
            int user_id = int.Parse(((DataRowView)t_USERBindingSource.Current)["user_id"].ToString());
            try
            {
                string CT_UseDUD = "";
                string CT_Mark = "";
                //  string CT_ID = ((DataRowView)user_crdBindingSource.Current)["CT_ID"].ToString();
                string CT_ID = comboBox1.SelectedValue.ToString();
                //查询卡类型有效时间
                DataTable dtct = cd_card.GetDataBy_CT_ID(int.Parse(CT_ID));
                string CT_DefaultUseDate = "";
                string CT_Pressure = "0";
                if (dtct.Rows.Count > 0)
                {
                    CT_UseDUD = dtct.Rows[0]["CT_UseDUD"].ToString();
                    CT_Mark = dtct.Rows[0]["CT_Mark"].ToString();
                    CT_DefaultUseDate = dtct.Rows[0]["CT_DefaultUseDate"].ToString();
                    CT_Pressure = dtct.Rows[0]["CT_Pressure"].ToString();
                    // yjTextBox.Text = CT_Pressure;
                }
 
                string fromdate = "";
                string to_date = "";
                if (CT_UseDUD == "False")
                {
                    //正式员工无时间限止
                    fromdate = fdateDateTimePicker.Value.ToShortDateString();

                    to_date = jdateDateTimePicker.Value.ToShortDateString();
                }
                else
                {
                    fromdate = fdateDateTimePicker.Value.ToShortDateString();
                    to_date = jdateDateTimePicker.Value.ToShortDateString();
                }

                //superma数据更新   获取人员的身份证号，去施普玛库是查询该人是否存在。不存在，提示用户人员未同步，不能发卡。
                SPMTableAdapters.TB_USER_CUSTOMINFOTableAdapter tb_user = new SPMTableAdapters.TB_USER_CUSTOMINFOTableAdapter();
                SPMTableAdapters.TB_USER_CARDTableAdapter tb_user_card = new SPMTableAdapters.TB_USER_CARDTableAdapter();

                string user_sfzh = sfzhTextBox.Text.ToString();
                DataTable super_user_dt = tb_user.GetDataBy_sfzh(user_sfzh);
                int super_user_dt_count = super_user_dt.Rows.Count;
                if (super_user_dt_count < 1)
                {
                    MessageBox.Show("施普玛中无此人员信息，请先同步该人员后，方可配卡！");
                    return;
                }
                else if (super_user_dt_count > 1)
                {
                    MessageBox.Show("施普玛中此人员信息存在多条，请确认该人员后，方可配卡！");
                    return;
                }

                //卡表插入一条记录
                //object kcardid = k_card.InsertQuery1(user_id, int.Parse(CT_ID), khTextBox.Text, "", Convert.ToDateTime(fromdate), Convert.ToDateTime(to_date), "发卡", 0);
                //卡表插入一条记录(更新插入语句，加入部分字段)
                decimal yj = 0;
                int login_user_id = 0;
                login_user_id = Convert.ToInt32(kwzx.Utils.CurrentUser.userid);
                yj = decimal.Parse(CT_Pressure);
                object kcardid = k_card.InsertQuery(user_id, int.Parse(CT_ID), khTextBox.Text, sMTextBox.Text.ToString(), null, Convert.ToDateTime(fromdate), Convert.ToDateTime(to_date), "发卡", 0, yj, login_user_id, null, null, null, null);
                
                khTextBox.Text = "";
                string CardID_dv = kcardid.ToString();//返回插入记录的ID    

                DataSet1TableAdapters.K_CarddataTableAdapter kcad = new DataSet1TableAdapters.K_CarddataTableAdapter();
                string CardtypeID2 = ((DataRowView)t_USERBindingSource.Current)["sfzh"].ToString();
                int CD_CardType = Convert.ToInt32(comboBox1.SelectedValue.ToString());
                string SM = sMTextBox.Text;
                int SXH = 0;
                DateTime czrq = DateTime.Now;
                string kzt = "发卡";
                string sh = "0";
                decimal thje = 0;
                string lrz = Utils.CurrentUser.xm;
                int xfzt = 0;
                DateTime zzrq = DateTime.Parse(jdateDateTimePicker.Value.ToString());
                
                //卡日志记录表
                kcad.Insert(user_id, CardtypeID2, CD_CardType, kh, SM, SXH, czrq, kzt, sh, thje, lrz, xfzt, zzrq);

                //设备下发表
                k_deviceIssue.InsertQuery(kh, "0", DateTime.Now, "K_Card", CardID_dv.ToString(), kzt, "");


                //superma数据更新
                //把卡号写入superma  仅有一条记录的时候，更新人员的卡号进去
                if (super_user_dt_count == 1)
                {
                    int spm_user_id = int.Parse(super_user_dt.Rows[0]["nUserIdn"].ToString());
                    DateTime utcNow = DateTime.Now.AddHours(8);
                    double utc = ConvertDateTimeInt(utcNow);

                    //代替页面上“取消发卡”功能里对施普玛软件的操作，在发卡时，删除旧卡号，配上新卡号
                    //这里要查询一下发卡记录表，看看sup_suer_id的人员信息在tb_user_card表中是否存在多条（>=1），在nLatest字段为1的记录
                    //若有的话，就要新增一条删除的记录，之后在配上一张发行卡
                    DataTable dtuser = tb_user_card.GetDataBy_nUserIdn_and_nLatest_1(spm_user_id);
                    if (dtuser.Rows.Count >= 1)
                    {
                        for (int i = 0; i < dtuser.Rows.Count; i++)
                        {
                            //TB_USER_CARD表数据例子
                            //8508	6215	2	2386104800	0	0	1382372898	0	0	1	0   发行卡
                            //8566	6215	1	2386104800	0	0	1382378937	0	0	2	0   删除卡
                            //8567	6215	1	0	        0	0	1382378937	0	0	1	0   零卡
                            //8568	6215	2	2386104800	0	0	1382378952	0	0	1	1   发行卡

                            //7199	8186	1	2670532624	0	0	1376408597	0	0	1	0   注册卡
                            //7986	8186	1	2670532624	0	0	1381940449	0	0	2	0   删除卡
                            //7987	8186	1	0	        0	0	1381940449	0	0	1	0   零卡
                            //7988	8186	2	2670532624	0	0	1381940472	0	0	1	1   发行卡

                            //获取卡ID
                            int old_nCardIdn = int.Parse(dtuser.Rows[i]["nCardIdn"].ToString());
                            //获取卡号
                            string old_sCardNo = dtuser.Rows[i]["sCardNo"].ToString();

                            //修改之前的卡设置nLatest字段为"0"
                            tb_user_card.UpdateQuery_nCardIdnIs0(old_nCardIdn);
                            //新增一条删除旧卡记录
                            tb_user_card.Insert(spm_user_id, 1, old_sCardNo, "0", 0, Convert.ToInt32(utc), 0, 0, 2, 0);
                            //重新配一张卡号为零的卡
                            tb_user_card.Insert(spm_user_id, 1, "0", "0", 0, Convert.ToInt32(utc), 0, 0, 1, 0);
                        }
                    }
                    //配一张新卡
                    tb_user_card.Insert(spm_user_id, 2, kh, "0", 0, Convert.ToInt32(utc), 0, 0, 1, 1);
                }

                DataSet2TableAdapters.M_user_accgrpTableAdapter useraccg = new DataSet2TableAdapters.M_user_accgrpTableAdapter();
                //添加权限
                //18全部生产区通行   20全部生产区(除中控中化)             
                useraccg.InsertQuery(20, user_id);

                //DDS数据更新
                string pcname_dds = Properties.Settings.Default.pcname_dds.ToString();
                string sfzh = sfzhTextBox.Text.ToString();
                string zSXM = xMTextBox.Text.ToString();
                string BMMC = dEPT_idTextBox.Text.ToString();

                //查询卡类型有效时间
                // DataTable dtct=  cd_card.GetDataBy_CT_UseDUD();

                Spread sp = new Spread();
                sp.StartConnect();
                sp.useradd(pcname_dds, sfzh, kh, zSXM, user_id.ToString(), BMMC, fromdate, to_date, "发卡");
                sp.DesInit();

                //表k_carddata 发卡日志表，加载参数userid的发卡日志
                this.k_CarddataTableAdapter.FillBy_user_id(this.dataSet1.K_Carddata, Convert.ToInt32(userid));

                //更新K_kwzxrw记录
                kwzxrw.UpdateQuery_czzt("已手动完成", kwzxrwid);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            button1.Enabled = false;
        }

        public double ConvertDateTimeInt(System.DateTime time)
        {
            double intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (time - startTime).TotalSeconds;
            return intResult;
        }

        public DateTime ConvertIntDatetime(double utc)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            startTime = startTime.AddSeconds(utc);
            startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 )
            return startTime;
        }

        /// <summary>
        /// 卡片打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string username1 = xMTextBox.Text;
            string bh1 = rybhTextBox.Text;
            string bm1 = uBYTextBox.Text;
            string jg1 = dEPT_idTextBox.Text;
            string lj1 = "";
            Image img1 = pictureBox1.Image;
            if (uBYTextBox.Text == "")
            {
                jg1 = uBYTextBox.Text;
                bm1 = dEPT_idTextBox.Text;
            }

            ZXPSampleCode.frmMultiPrint frmmu = new ZXPSampleCode.frmMultiPrint("", username1, bh1, bm1, jg1, lj1, img1);
            frmmu.ShowDialog();
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
